<template>
  <div> 
    <el-card shadow="never" class="mb-5 border-box">
    <el-row :gutter="12">
      <el-col :xs="24" :sm="12" :lg="8">
        <el-input 
          v-model="searchForm.deptName" 
          placeholder="部门名称" 
          class="search-input"
          :prefix-icon="Search"
          clearable
           @input="handleSearch"></el-input>
      </el-col>
      <el-col :xs="24" :sm="12" :lg="8" class="el-col2">
        <el-button type="primary" @click="showDialog('add')">
          <el-icon><Plus /></el-icon>
          新增部门
        </el-button>
      </el-col>
    </el-row>
  </el-card>
    <div class="page-content">
    <el-table 
      :data="tableData" 
      v-loading="loading"
      row-key="id"
      height="calc(100vh - 265px)"
    >
      <el-table-column 
        prop="deptName" 
        label="部门名称"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column prop="deptInfo" label="部门描述" />
      <el-table-column prop="managerNames" label="部门管理人员" />
      <el-table-column prop="createTime" label="创建时间" >
        <template #default="scope">
          {{scope.row.createTime ? useDateFormat(scope.row.createTime, 'YYYY-MM-DD') : ''}}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="400px">
        <template #default="scope">
          <el-button type="primary"  size="small" link @click="showDialog('edit', scope.row)">
            <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger"  size="small" link @click="deleteDepartment(scope.row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
            <el-button type="success"  size="small" link @click="addDepartmentDialog('add', scope.row)">
              <el-icon><Plus /></el-icon>
              新增
            </el-button>
            <el-button type="warning"  size="small" link @click="bindingDialog('binding', scope.row)">
              <el-icon><Link /></el-icon>
              绑定人员
            </el-button>
            <el-button type="info"  size="small" link @click="bindingDialog('Unbind', scope.row)">
              <el-icon><CircleClose /></el-icon>
              解绑人员
            </el-button>
          <!-- <el-row>
            <ArtButtonMore
              :list="operateList"
              @click="buttonMoreClick($event, scope.row)"
            />
          </el-row> -->
        </template>
      </el-table-column>
    </el-table>
    </div>
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加部门' : '编辑部门'"
      width="50%"
      @closed="resetForm(formRef)"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
        <el-form-item label="部门名称" prop="deptName">
          <el-input v-model="formData.deptName" />
        </el-form-item>
        <el-form-item label="部门描述" prop="deptInfo">
          <el-input v-model="formData.deptInfo" type="textarea" />
        </el-form-item>
        <el-form-item label="部门管理人员" prop="sysDeptManagerBoList">
          <el-select
            v-model="selectedManagers"
            multiple
            filterable
            remote
            :remote-method="handleManagerSearch"
            :loading="userLoading"
            placeholder="请选择部门管理人员"
            style="width: 100%"
            @change="handleUserSelectionChange"
            @scroll="handleUserSelectScroll"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.id || ''"
              :label="item.usrName || ''"
              :value="item.id || '0'"
            >
              <span>{{ item.usrName || '' }}</span>
              <span class="user-info">{{ item.usrPhone || '' }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetForm(formRef)">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 绑定解绑 -->
    <el-dialog
      v-model="bindDialogVisible"
      :title="bindDialogType === 'binding' ? '绑定人员' : '解绑人员'"
      width="50%"
      @closed="resetBindForm"
    >
      <el-form  :model="formData" label-width="120px">
        <el-form-item label="选择人员" prop="selectedUsers">
          <el-select
            v-model="selectedUsers"
            multiple
            filterable
            remote
            :remote-method="handleManagerSearch"
            :loading="userLoading"
            placeholder="请选择人员"
            style="width: 100%"
            @scroll="handleUserSelectScroll"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.id || ''"
              :label="item.usrName || ''"
              :value="item.id || 0"
            >
              <span>{{ item.usrName || '' }}</span>
              <span class="user-info">{{ item.usrPhone || '' }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetBindForm">取消</el-button>
          <el-button type="primary" @click="submitBinding">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ElMessageBox, ElMessage } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { Search } from '@element-plus/icons-vue'
  import { useDateFormat } from '@vueuse/core'
  import { ButtonMoreItem } from '@/components/core/forms/ArtButtonMore.vue'
  import { 
    sysDeptListDeptUsingPost, 
    sysDeptSaveDeptUsingPost, 
    sysDeptDeleteDeptByIdUsingPost,
    sysDeptGetDeptByIdUsingPost,
    sysDeptUpdateDeptUsingPost,
    sysDeptBindUsrDeptDeptIdUsingPost,
    sysDeptUnBindUsrDeptDeptIdUsingPost,
    sysDeptShowDeptUserUsingGet,
  } from '@/api/4a/bumen'
  import { sysUserPageUserUsingPost } from '@/api/4a/yonghu'
  import type { SysDeptduixiang, SysUserduixiang, bumenguanlirenyuanxinxi } from '@/api/4a/types'
import { log } from 'console'
  
  const dialogType = ref('add')
  const dialogVisible = ref(false)
  const loading = ref(false)
  const selectedManagers = ref<number[]>([])
  const formRef = ref<FormInstance>()

  const formData = reactive({
    id: null,
    deptName: '',
    deptInfo: '',
    deptParId: 1,
    sysDeptManagerBoList: [] as any
  })

  const searchForm = reactive({
    deptName: ''
  })

  // 分页参数
  const pagination = reactive({
    current: 1,
    size: 10,
    total: 0
  })

  // 绑定/解绑对话框相关
  const bindDialogVisible = ref(false)
  const bindDialogType = ref('')
  const currentDeptId = ref<number>(0)
  const selectedUsers = ref<number[]>([])

  // 操作列表
  const operateList = ref([
    { key: 'edit', label: '编辑' },
    { key: 'delete', label: '删除' },
    { key: 'addDepartment', label: '新增部门' },
    { key: 'binding', label: '绑定人员' },
    { key: 'Unbind', label: '解绑人员' },
  ])

  interface DeptTableItem extends SysDeptduixiang {
    managerNames?: string;
    hasChildren?: boolean;
    children?: DeptTableItem[];
    sysDeptVoList?: DeptTableItem[];
  }

  interface PageResponse {
    list: SysDeptduixiang[];
    total: number;
  }

  // 列表数据
  const tableData = ref<DeptTableItem[]>([])
  
  const rules = reactive<FormRules>({
    deptName: [
      { required: true, message: '请输入部门名称', trigger: 'blur' },
    ],
    deptInfo: [
      { required: true, message: '请输入部门描述', trigger: 'blur' }
    ],
    sysDeptManagerBoList: [
      { required: true, message: '请选择部门管理人员', trigger: 'change' }
    ]
  })

  // 用户列表数据
  const userOptions = ref<SysUserduixiang[]>([])
  const userLoading = ref(false)
  const userPagination = reactive({
    current: 1,
    size: 10,
    total: 0
  })

  // 处理部门管理人员显示
  const processManagerList = (dept: SysDeptduixiang) => {
    if (dept.sysDeptManagerVoList) {
      return dept.sysDeptManagerVoList.map((item: bumenguanlirenyuanxinxi) => item.usrName || '').join(',')
    }
    return ''
  }

  // 获取列表数据
  const getTableData = async () => {
    try {
      loading.value = true
      const res = await sysDeptListDeptUsingPost({
        body: {
          ...searchForm
        }
      })
      if(res.code === 0 && res.data){
        // 处理每个部门的管理人员显示和树状结构
        const processData = (deptList: SysDeptduixiang[]): DeptTableItem[] => {
          return deptList.map((dept): DeptTableItem => {            
            const hasChildren = Array.isArray(dept.sysDeptVoList) && dept.sysDeptVoList.length > 0
            const children = hasChildren ? processData(dept.sysDeptVoList || []) : []
            return {
              id: dept.id || 0,
              deptName: dept.deptName || '',
              deptInfo: dept.deptInfo || '',
              createTime: dept.createTime || '',
              managerNames: processManagerList(dept),
              children: children.length > 0 ? children : undefined
            }
          })
        }
        
        tableData.value = processData(res.data)
      }else{
        tableData.value = []
      }
    } catch (error) {
      console.error('获取部门列表失败:', error)
      ElMessage.error('获取部门列表失败')
    } finally {
      loading.value = false
    }
  }

  // 搜索
  const handleSearch = () => {
    pagination.current = 1
    getTableData()
  }


  // 取消部门添加表单
   const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    dialogVisible.value = false
    formEl.resetFields()
    selectedManagers.value = []
  }

  // 获取部门详情
  const getDeptDetail = async (id: number) => {
    try {
      loading.value = true
      const response = await sysDeptGetDeptByIdUsingPost({
        body: { id }
      })
      
      if (response.data) {
        Object.assign(formData, response.data)
        const sysDeptManagerVoList = response.data.sysDeptManagerVoList
        // 设置管理人员
        if (sysDeptManagerVoList) {
          selectedManagers.value = sysDeptManagerVoList.map(manager => manager.usrId || 0)
          formData.sysDeptManagerBoList = sysDeptManagerVoList.map(manager => ({
            deptId: manager.deptId || 0,
            usrId: manager.usrId || 0
          }))
          
        }
      } else {
        ElMessage.error(response.msg || '获取部门详情失败')
      }
    } catch (error) {
      console.error('获取部门详情失败:', error)
      ElMessage.error('获取部门详情失败')
    } finally {
      loading.value = false
    }
  }

  // 新增部门
  const addDepartmentDialog = async (type: string, row?: SysDeptduixiang) => {
    dialogType.value = type
    dialogVisible.value = true
    formData.deptParId = row?.id || 0
    formData.id = null
  }

  // 编辑
  const showDialog = async (type: string, row?: SysDeptduixiang) => {
    dialogType.value = type
    dialogVisible.value = true
    console.log(type);
    console.log(row);
    
    if (type === 'edit' && row?.id) {
      await getDeptDetail(row.id)
    } else {
      // resetForm(formRef.value)
    }
  }

  // 删除
  const deleteDepartment = async (row: SysDeptduixiang) => {
    try {
      await ElMessageBox.confirm('确定要删除该部门吗？', '删除部门', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      loading.value = true
      const response = await sysDeptDeleteDeptByIdUsingPost({
        body: [row.id || 0]
      })
      
      if (response.data) {
        ElMessage.success('删除成功')
        getTableData() // 刷新列表
      } else {
        ElMessage.error(response.msg || '删除失败')
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除部门失败:', error)
        ElMessage.error('删除部门失败')
      }
    } finally {
      loading.value = false
    }
  }

  // 绑定人员
  const bindingDialog = async (type: string, row: SysDeptduixiang) => {
    bindDialogType.value = type
    bindDialogVisible.value = true
    currentDeptId.value = row.id || 0
    selectedUsers.value = []
    const response = await sysDeptShowDeptUserUsingGet({
      params : {
          deptId: currentDeptId.value,
        }
      })
      if (response.data) {
        selectedUsers.value = response.data.map(user => user.id || 0)
      }
    // // 如果是解绑，需要回显已绑定人员
    // if (type === 'Unbind' ) {
    //   const response = await sysUserPageUserUsingPost({
    //     body: {
    //       deptId: currentDeptId.value,
    //       current: 1,
    //       size: 100,
    //     }
    //   })
    //   if (response.data?.list) {
    //     selectedUsers.value = response.data.list.map(user => Number(user.id) || 0)
    //   }
    // }
    
    // 重新加载用户列表
    await getUserList()
  }

  // 新增部门提交
  const submitForm = async () => {
    if (!formRef.value) return
    try {
      await formRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true   
          if(formData.id){
            const response = await sysDeptUpdateDeptUsingPost({
            body: formData
            })
            
            if (response.data) {
              ElMessage.success('修改成功')
              dialogVisible.value = false
              getTableData() // 刷新列表
            } else {
              ElMessage.error(response.msg)
            }
          }else{
            const response = await sysDeptSaveDeptUsingPost({
            body: formData
            })
            
            if (response.data) {
              ElMessage.success('添加成功')
              dialogVisible.value = false
              getTableData() // 刷新列表
            } else {
              ElMessage.error(response.msg)
            }
          }
        
        }
      })
    } catch (error) {
      ElMessage.error('保存部门失败')
    } finally {
      loading.value = false
    }
  }

  // 绑定/解绑提交
  const submitBinding = async () => {
    if (!selectedUsers.value.length) {
      ElMessage.warning('请选择人员')
      return
    }

    try {
      loading.value = true
      let response
      
      if (bindDialogType.value === 'binding') {
        response = await sysDeptBindUsrDeptDeptIdUsingPost({
          params: { deptId: currentDeptId.value },
          body: selectedUsers.value
        })
      } else {
        response = await sysDeptUnBindUsrDeptDeptIdUsingPost({
          params: { deptId: currentDeptId.value },
          body: selectedUsers.value
        })
      }

      if (response.code == 0) {
        ElMessage.success(bindDialogType.value === 'binding' ? '绑定成功' : '解绑成功')
        bindDialogVisible.value = false
        getTableData() // 刷新列表
      } else {
        ElMessage.error(response.msg || (bindDialogType.value === 'binding' ? '绑定失败' : '解绑失败'))
      }
    } catch (error) {
      console.error(bindDialogType.value === 'binding' ? '绑定人员失败:' : '解绑人员失败:', error)
      ElMessage.error(bindDialogType.value === 'binding' ? '绑定人员失败' : '解绑人员失败')
    } finally {
      loading.value = false
    }

  }
  // 重置绑定表单
  const resetBindForm = () => {
    bindDialogVisible.value = false
    selectedUsers.value = []
  }

  // 操作
  const buttonMoreClick = (item: ButtonMoreItem, row: SysDeptduixiang) => {
    if (item.key === 'delete') {
      // 删除
      deleteDepartment(row)
    } else if (item.key === 'edit') {
      // 编辑
      showDialog('edit', row)
    } else if (item.key === 'addDepartment') {
      // 新增部门
      addDepartmentDialog('add', row)
    }else if (item.key === 'binding') {
      // 绑定人员
      bindingDialog('binding', row)
    } else if (item.key === 'Unbind') {
      // 解绑人员
      bindingDialog('Unbind', row)
    }
  }

  // 搜索用户
  const handleManagerSearch = async (query: string) => {
    if (query) {
      userPagination.current = 1
      await getUserList(query)
    }
  }

  // 获取用户列表
  const getUserList = async (searchKey?: string) => {
    try {
      userLoading.value = true
      const { data } = await sysUserPageUserUsingPost({
        body: {
          current: userPagination.current,
          size: userPagination.size,
          usrName: searchKey
        }
      })
      if (data?.list) {
        if (userPagination.current === 1) {
          userOptions.value = data.list
        } else {
          userOptions.value = [...userOptions.value, ...data.list]
        }
        userPagination.total = data.total || 0
      }
    } catch (error) {
      console.error('获取用户列表失败:', error)
      ElMessage.error('获取用户列表失败')
    } finally {
      userLoading.value = false
    }
  }

  // 用户选择改变时更新部门管理人员列表
  const handleUserSelectionChange = (values: number[]) => {
    formData.sysDeptManagerBoList = values.map(usrId => ({
      deptId: 0,
      usrId: usrId || 0
    }))
  }

  // 用户下拉框滚动到底部时加载更多
  const handleUserSelectScroll = async (event: Event) => {
    const target = event.target as HTMLElement
    const { scrollTop, clientHeight, scrollHeight } = target
    const isBottom = Math.ceil(scrollTop + clientHeight) >= scrollHeight
    
    if (isBottom && !userLoading.value && userOptions.value.length < userPagination.total) {
      userPagination.current++
      await getUserList()
    }
  }

  // 初始化获取数据
  onMounted(() => {
    getTableData()
    getUserList() // 初始加载用户列表
  })
</script>

<style lang="scss" scoped>
  .page-content {
    .svg-icon {
      width: 1.8em;
      height: 1.8em;
      overflow: hidden;
      vertical-align: -8px;
      fill: currentcolor;
    }

    .el-col2 {
      display: flex;
      gap: 12px;
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }

    .user-info {
      margin-left: 8px;
      color: #999;
      font-size: 13px;
    }
  }
  .border-box {
    border-radius: 8px !important;
  }
</style>

